Back

Understanding Collection+JSON in RESTful APIs

Collection+JSON is a lightweight format designed for working with collections in RESTful APIs. It's great for handling lists, like tasks or users, and makes it easy for clients to interact with APIs.

Structure

A typical Collection+JSON response includes:

  • collection: The main object containing metadata, items, and actions.
  • items: Each item has its own URI and data.
  • links: Navigation links (e.g., "next", "prev").
  • queries: Predefined queries clients can use.
  • template: A structure for creating or updating items.

Example

Here’s a simple Collection+JSON response for a "tasks" API:
 

{
  "collection": {
    "href": "http://api.example.com/tasks",
    "items": [
      {
        "href": "http://api.example.com/tasks/1",
        "data": [
          { "name": "title", "value": "Buy groceries" },
          { "name": "status", "value": "pending" }
        ]
      },
      {
        "href": "http://api.example.com/tasks/2",
        "data": [
          { "name": "title", "value": "Clean the house" },
          { "name": "status", "value": "completed" }
        ]
      }
    ],
    "template": {
      "data": [
        { "name": "title", "prompt": "Task title" },
        { "name": "status", "prompt": "Task status" }
      ]
    }
  }
}

Benefits

  1. Standardized: Clients can understand the API without custom documentation.
  2. Hypermedia-driven: APIs guide clients using links, templates, and queries.
  3. Flexible: Easy to evolve over time without breaking clients.
json collection+json
Posted To avatar
Programming
• 7 months ago

Please login or create an account to post a comment.

No Posts
No comments yet...